%% Copyright (C) 2007 Vijay Gajula <gajulak@gmail.com>.
%% All rights reserved.
%%
%% Redistribution and use in source and binary forms, with or without
%% modification, are permitted provided that the following conditions
%% are met:
%%
%% 1. Redistributions of source code must retain the above copyright
%%    notice, this list of conditions and the following disclaimer.
%% 2. Redistributions in binary form must reproduce the above
%%    copyright notice, this list of conditions and the following
%%    disclaimer in the documentation and/or other materials provided
%%    with the distribution.
%%
%% THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
%% OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
%% WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
%% ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
%% DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
%% DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
%% GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
%% INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
%% WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
%% NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
%% SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

-module(client).
-export([start/0,start/2]).

%% start()->
 %% start({127,0,0,1}, 5454).
start()->
 start({192,168,1,1}, 5454).
start(Host,Port) ->
		application:start(ssl),
		{ok, CSock} = ssl:connect(Host, Port,
				  [{active, false},
				   {certfile, "../client/certs/client.cert"},
                                   {keyfile, "../client/certs/client.key"},
                                   {cacertfile, "../CAServer/cacert.pem"},
                                   {verify, 0},
                                   {depth, 0}]),

		io:format("Connect: connected.~n"),
		{ok, _Cert} = ssl:peercert(CSock),
		%% Cert = ssl:peercert(CSock),
		%% erlang:display(Cert),
		%% io:fwrite("Connet: peer cert:~n~p~n", [Cert1]),
		%% Info = ssl:connection_info(CSock),
		test_module(CSock, "../client/sys.xml"),
		%% test_module(CSock, "../client/route.xml"),
		%% test_module(CSock, "../client/interface.xml"),
		%% test_module(CSock, "../client/interface_set.xml"),
		%% test_module(CSock, "../client/route_set.xml"),

		io:fwrite("Connect:closing and terminating.~n"),
		ssl:close(CSock),
		application:stop(ssl).
		
test_module(CSock, Filename) ->
	{ok,Fd}=file:open(Filename,[read,raw]),
	{ok, Buf} = file:read(Fd, 2048),
	ssl:send(CSock, Buf),
	{ok, Data} = ssl:recv(CSock, 0),
	io:fwrite("Connect: got data :~s~n", [Data]),
	file:close(Fd).

